package com.example.sunny.service.work

import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.annotation.UiThread
import androidx.core.app.NotificationCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.Transformations
import androidx.work.CoroutineWorker
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.example.sunny.R
import com.example.sunny.SunnyApplication
import com.example.sunny.pojo.location.MyLocation
import com.example.sunny.pojo.weather.Weather
import com.example.sunny.pojo.weather.getSky
import com.example.sunny.service.Repository
import com.example.sunny.service.network.location.LocationService
import com.example.sunny.view.weather.WeatherActivity

class WeatherNotificationWorker(val context: Context,workerParameters: WorkerParameters):Worker(context,workerParameters),LocationService.MyLocationListener.LocationCallback{
    var myLocation = MutableLiveData<MyLocation>()
    override  fun doWork(): Result {
        Log.d("WeatherNotificationWorker","dowork开始")
        //开启定位
        val locationClient = LocationService.initLocation(context,this)

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        Handler(Looper.getMainLooper()).post{
            val weatherLiveData = Transformations.switchMap(myLocation){myLocation->
                Repository.refreshWeather(myLocation.lng.toString(),myLocation.lat.toString(),context)
            }

            val observer = Observer<kotlin.Result<Weather>>{result->
                val weather = result.getOrNull()
                if (weather!=null){
                    myLocation.value?.apply {
                        val temperature = weather.daily.temperature[0].run {
                            "${min.toInt()}~${max.toInt()} ℃"
                        }
                        val skycon = getSky(weather.daily.skycon[0].value).info
                        val cintent = Intent(SunnyApplication.context, WeatherActivity::class.java)
                        val pendingIntent = PendingIntent.getActivity(SunnyApplication.context, 0, cintent, PendingIntent.FLAG_UPDATE_CURRENT)

                        val notification = NotificationCompat.Builder(SunnyApplication.context, "weather")
                            .setContentTitle("桑尼向您推送今天的天气~")
                            .setContentText("$city 天气:$skycon 温度:$temperature")
                            .setSmallIcon(R.drawable.ic_clear_day)
                            .setLargeIcon(BitmapFactory.decodeResource(context.resources, getSky(weather.daily.skycon[0].value).icon))
                            .setContentIntent(pendingIntent)
                            .setAutoCancel(true)
                            .build()

                        notificationManager.notify(1, notification)
                        Log.d("AlarmService","通知已推送")
                    }
                }else{
                    Result.retry()
                }
            }
            weatherLiveData.observeForever(observer)
        }

        return Result.success()
    }

    override fun getLocation(myLocation: MyLocation) {
        this.myLocation.value = myLocation
    }


}